<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Android, Java">










<meta name="description" content="哈哈~">
<meta name="keywords" content="zachaxy">
<meta property="og:type" content="website">
<meta property="og:title" content="zachaxy">
<meta property="og:url" content="https://zachaxy.github.io/page/9/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="哈哈~">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="zachaxy">
<meta name="twitter:description" content="哈哈~">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/page/9/">





  <title>zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">

  <section id="posts" class="posts-expand">









  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/13/setContentView内部原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/13/setContentView内部原理/" itemprop="url">setContentView内部原理</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-13T23:49:53+08:00">
                2017-05-13
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  300
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>我们平时在写Android界面的时候，一般都是创建一个Activity（eg：MainActivity.java），并创建一个对应的布局文件（eg：activity_main.xml），然后在Activity的onCreate方法中，调用setContentView(R.layout.activity_main)，这样布局文件中所展示的界面就能显示出来了。相信刚开始学习Android时，这一步骤是让我们的界面显示出来的必经套路，那么其内部究竟执行了什么，才能实现这一效果？今天就一起来了解一下setContentView方法的内部实现原理。</p>
</blockquote>
<h1 id="早期的setContentView方法"><a href="#早期的setContentView方法" class="headerlink" title="早期的setContentView方法"></a>早期的setContentView方法</h1><p>之前我们在编写Android程序的时候，创建的XXXActivity默认都是继承Activity这个类的，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> <span class="keyword">extends</span> <span class="title">Activity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        getWindow().requestFeature(Window.FEATURE_NO_TITLE);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>进入setContentView方法中一探究竟：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setContentView</span><span class="params">(@LayoutRes <span class="keyword">int</span> layoutResID)</span> </span>&#123;</span><br><span class="line">    getWindow().setContentView(layoutResID);</span><br><span class="line">    initWindowDecorActionBar();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到其实Activity中的setContentView方法自己并没有执行上面逻辑，而是调用了与Activity关联的Window的setContentView，</p>
<h1 id="现在的setContentView方法"><a href="#现在的setContentView方法" class="headerlink" title="现在的setContentView方法"></a>现在的setContentView方法</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> <span class="keyword">extends</span> <span class="title">AppcompatActivity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        getWindow().requestFeature(Window.FEATURE_NO_TITLE);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/13/手写JVM系列-9-指令集/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/13/手写JVM系列-9-指令集/" itemprop="url">手写JVM系列(9)-指令集</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-13T23:03:42+08:00">
                2017-05-13
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,199
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>编译之后的 Java 方法以字节码的形式存储在 class 文件中。前面已经初步实现了 Java 虚拟机栈、帧、操作数栈和局部变量表等运行时数据区。那么 JVM 是如何操作局部变量表和操作数栈中的数据呢？这就涉及到了 JVM 的字节码指令集。这一节对 JVM 的字节码指令集做一个介绍，本节所实现的指令位于<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目</a>的 instructions 包下。</p>
</blockquote>
<h1 id="字节码简介"><a href="#字节码简介" class="headerlink" title="字节码简介"></a>字节码简介</h1><p>字节码是运行在虚拟机上的机器码,每一个类或者接口都会被 Java 编译器编译成一个 class 文件，类或接口的方法信息就放在 class 文件的 method_info 结构中。如果方法不是抽象的，也不是本地方法，方法的 Java 代码就会被编译器编译成字节码（即使方法是空的，编译器也会生成一条 return 语句），存放在 method_info 结构的<strong>Code 属性</strong>中。 ==&gt; 字节码一般来说是针对方法中的步骤的；</p>
<h1 id="指令简介"><a href="#指令简介" class="headerlink" title="指令简介"></a>指令简介</h1><p>字节码中存放编码后的 Java 虚拟机指令。</p>
<p><strong>指令 = 操作码 + 操作数（如果有的话）</strong></p>
<ul>
<li>操作码（Opcode）：一个字节长度，代表着某种特定操作含义。</li>
<li>操作数（Operands）：操作码后面需要跟零到多个代表该操作码所需的参数。</li>
</ul>
<p>所以 Java 虚拟机使用的是<strong>变长指令</strong></p>
<p>如果把指令想象成函数的话，操作数就是它的参数。每条指令都以一个单字节的操作码（opcode）开头。由于只使用一字节表示操作码，显而易见，Java 虚拟机最多只能支持 256（2^8 ）条指令。</p>
<p>Java 虚拟机规范已经定义了 205 条指令，操作码分别是 0（0x00）到 202（0xCA）、254（0xFE）和 255（0xFF）。这 205 条指令构成了 Java 虚拟机的指令集（instruction set）。</p>
<p>字节码指令是一种具有鲜明特点，优劣势都很突出的指令集架构。</p>
<p>缺点：由于 Class 文件格式放弃了将编译后操作数长度对齐，那么如果处理那些超过一个字节的数据时，不得不在运行时从字节中重建出具体数据，eg：将一个 16 位无符号整数用两字节（byte1，byte2）存储起来，那么在读取该 16 位整数时，需要这样转换：<code>( byte1 &lt;&lt; 8 ) | byte2</code>，这导致解释执行操作码时损失了一些性能。</p>
<p>优点：放弃了操作数长度对其，意味着可以省略很多填充和间隔符号，尽可能获取短小精干的编译代码（小数据量，高效传输）</p>
<h1 id="操作码的数据类型"><a href="#操作码的数据类型" class="headerlink" title="操作码的数据类型"></a>操作码的数据类型</h1><p>为了让编码后的字节码更加紧凑，很多操作码本身就隐含了操作数，比如把常数 0 推入操作数栈的指令是 iconst_0。</p>
<p><strong>操作数栈</strong>和<strong>局部变量表</strong>只存放数据的值，并不记录数据类型。结果就是：<strong>指令必须知道自己在操作什么类型的数据。</strong>这一点也直接反映在了操作码的助记符上。</p>
<p>例如：</p>
<p>iadd 指令就是对 int 值进行加法操作；</p>
<p>dstore 指令把操作数栈顶的 double 值弹出，存储到局部变量表中；</p>
<p>areturn 从方法中返回引用值。</p>
<p>也就是说，如果某类指令可以操作不同类型的变量，则助记符的<strong>第一个字母表示变量类型</strong>。</p>
<table>
<thead>
<tr>
<th>助记符首字母</th>
<th>数据类型</th>
<th>例子</th>
</tr>
</thead>
<tbody><tr>
<td>a</td>
<td>reference</td>
<td>aload、astore、areturn</td>
</tr>
<tr>
<td>b</td>
<td>byte/boolean</td>
<td>bipush、baload</td>
</tr>
<tr>
<td>c</td>
<td>char</td>
<td>caload、castore</td>
</tr>
<tr>
<td>d</td>
<td>double</td>
<td>dload、dstore、dadd</td>
</tr>
<tr>
<td>f</td>
<td>float</td>
<td>fload、fstore、fadd</td>
</tr>
<tr>
<td>i</td>
<td>int</td>
<td>iload、istore、iadd</td>
</tr>
<tr>
<td>l</td>
<td>long</td>
<td>lload、lstore、ladd</td>
</tr>
<tr>
<td>s</td>
<td>short</td>
<td>sipush、sastore</td>
</tr>
</tbody></table>
<p>并非每个基本数据类型都有对应的操作码，从上图可以看到大部指令都没有直接支持 byte、char、short、boolean，编译器会在编译器或者运行期将 byte 和 short 类型的数据<strong>带符号扩展</strong>为相应的 int 类型，将 boolean 和 char 类型数据<strong>零位扩展</strong>为相应的 int 类型。因此，大多数对于 byte、char、short、boolean 的操作，实际上都是使用相应的 int 类型作为运算类型。</p>
<h1 id="指令的分类"><a href="#指令的分类" class="headerlink" title="指令的分类"></a>指令的分类</h1><p>因为使用一字节表示操作码，所以 Java 虚拟机最多只能支持 256（2^8 ）条指令。</p>
<p>Java 虚拟机规范已经定义了 205 条指令，操作码分别是 0（0x00）到 202（0xCA）、254（0xFE）和 255（0xFF）。这 205 条指令构成了 Java 虚拟机的指令集（instruction set）。</p>
<p>Java 虚拟机规范把已经定义的 205 条指令按用途分成了 11 类：</p>
<ol>
<li>常量（constants）指令</li>
<li>加载（loads）指令</li>
<li>存储（stores）指令</li>
<li>操作数栈（stack）指令</li>
<li>数学（math）指令</li>
<li>转换（conversions）指令</li>
<li>比较（comparisons）指令</li>
<li>控制（control）指令</li>
<li>引用（references）指令</li>
<li>扩展（extended）指令</li>
<li>保留（reserved）指令</li>
</ol>
<p>注:保留指令共有 3 条。其中一条是留给调试器的，用于实现断点，操作码是<code>202（0xCA）</code>，助记符是<code>breakpoint</code>。另外两条留给<code>Java</code>虚拟机实现内使用，操作码分别是<code>254（0xFE）</code>和<code>266（0xFF）</code>，助记符是<code>impdep1</code>和<code>impdep2</code>。这三条指令不允许出现在 class 文件中。</p>
<p>接下来这上述的 11 类指令做一个简单的介绍，并在每种类别的指令中跳出几个有代表性的进行简要说明。</p>
<h1 id="常量指令"><a href="#常量指令" class="headerlink" title="常量指令"></a>常量指令</h1><p>常量指令把常量<strong>推入操作数栈顶</strong>。常量可以来自三个地方：隐含在操作码里、操作数和运行时常量池。</p>
<h2 id="nop-指令"><a href="#nop-指令" class="headerlink" title="nop 指令"></a>nop 指令</h2><p>nop 指令是最简单的一条指令，因为它什么也不做。</p>
<h2 id="const-系列指令"><a href="#const-系列指令" class="headerlink" title="const 系列指令"></a>const 系列指令</h2><p>这一系列指令把隐含在操作码中的常量值<strong>推入操作数栈顶</strong>。几个具体的例子如下：</p>
<ul>
<li><p>aconst_null 指令把 null 引用推入操作数栈顶</p>
</li>
<li><p>dconst_0 指令把 double 型 0 推入操作数栈顶</p>
</li>
<li><p>iconst_m1 指令把 int 型 -1 推入操作数栈顶</p>
<p>​</p>
</li>
</ul>
<h2 id="bipush-和-sipush-指令"><a href="#bipush-和-sipush-指令" class="headerlink" title="bipush 和 sipush 指令"></a>bipush 和 sipush 指令</h2><p>bipush 指令从<strong>操作数</strong>中获取一个 byte 型整数，扩展成 int 型，然后<strong>推入栈顶</strong>。</p>
<p>sipush 指令从<strong>操作数</strong>中获取一个 short 型整数，扩展成 int 型，然后<strong>推入栈顶</strong>。</p>
<h1 id="加载指令"><a href="#加载指令" class="headerlink" title="加载指令"></a>加载指令</h1><p>加载指令从局部变量表获取变量，然后推入操作数栈顶。加载指令共 33 条，按照所操作变量的类型可以分为 6 类:</p>
<ol>
<li>aload 系列指令操作引用类型变量</li>
<li>dload 系列操作 double 类型变量</li>
<li>fload 系列操作 float 变量</li>
<li>iload 系列操作 int 变量</li>
<li>lload 系列操作 long 变量</li>
<li>xaload 操作数组</li>
</ol>
<h1 id="存储指令"><a href="#存储指令" class="headerlink" title="存储指令"></a>存储指令</h1><p>和加载指令刚好相反，存储指令把变量从操作数栈顶弹出，然后存入局部变量表。</p>
<h1 id="栈指令"><a href="#栈指令" class="headerlink" title="栈指令"></a>栈指令</h1><p>直接对<strong>操作数栈</strong>进行操作，栈指令并不关心变量类型（但是可以确定不是 long 和 double，因为这两种类型占用两个 Slot，所以这里虽然不管类型，但是可以确定是占用了一个 Slot）。共 9 条：</p>
<ul>
<li>pop 和 pop2 指令将栈顶变量弹出</li>
<li>dup 系列指令复制栈顶变量</li>
<li>swap 指令交换栈顶的两个变量</li>
</ul>
<h1 id="数学指令"><a href="#数学指令" class="headerlink" title="数学指令"></a>数学指令</h1><p>数学指令大致对应 Java 语言中的加、减、乘、除等数学运算符。</p>
<p>数学指令共 37 条，包括：</p>
<ul>
<li>算术指令</li>
<li>位移指令</li>
<li>布尔运算指令</li>
<li>自增指令(eg:i++)</li>
</ul>
<h2 id="算术指令"><a href="#算术指令" class="headerlink" title="算术指令"></a>算术指令</h2><ol>
<li>加法（add）指令</li>
<li>减法（sub）指令</li>
<li>乘法（mul）指令</li>
<li>除法（div）指令</li>
<li>求余（rem）指令</li>
<li>取反（neg）指令</li>
</ol>
<h2 id="位移指令"><a href="#位移指令" class="headerlink" title="位移指令"></a>位移指令</h2><ol>
<li><p>左移</p>
</li>
<li><p>右移</p>
<ol>
<li>算术右移（有符号右移）</li>
<li>逻辑右移（无符号右移）</li>
</ol>
<p>​</p>
</li>
</ol>
<h2 id="布尔运算指令"><a href="#布尔运算指令" class="headerlink" title="布尔运算指令"></a>布尔运算指令</h2><p>布尔运算指令只能操作 int 和 long 变量：</p>
<ol>
<li>按位与（and）</li>
<li>按位或（or）</li>
<li>按位异或（xor）</li>
</ol>
<h2 id="iinc-指令"><a href="#iinc-指令" class="headerlink" title="iinc 指令"></a>iinc 指令</h2><p>iinc 指令给局部变量表中的 int 变量增加常量值，局部变量表索引和常量值都由指令的操作数提供。</p>
<h1 id="类型转换指令"><a href="#类型转换指令" class="headerlink" title="类型转换指令"></a>类型转换指令</h1><p>类型转换指令可以分为 4 种：</p>
<ul>
<li>i2x 系列指令把 int 变量强制转换成其他类型</li>
<li>l2x 系列指令把 long 变量强制转换成其他类型</li>
<li>f2x 系列指令把 float 变量强制转换成其他型</li>
<li>d2x 系列指令把 double 变量强制转换成其他类型</li>
</ul>
<p>注意:引用类型转换对应的是 checkcast 指令,在后面的章节会出现。</p>
<h1 id="比较指令"><a href="#比较指令" class="headerlink" title="比较指令"></a>比较指令</h1><p>比较指令可以分为两类：</p>
<ul>
<li>将比较结果推入操作数栈顶。</li>
<li>根据比较结果跳转。</li>
</ul>
<h2 id="lcmp-指令"><a href="#lcmp-指令" class="headerlink" title="lcmp 指令"></a>lcmp 指令</h2><p>用于比较 long 变量,把栈顶的两个 long 变量弹出，进行比较，然后把比较结果（int 型 0、1 或 -1）推入栈顶。</p>
<h2 id="fcmp-指令"><a href="#fcmp-指令" class="headerlink" title="fcmp 指令"></a>fcmp 指令</h2><p>指令和 lcmp 指令很像，但是除了比较的变量类型不同以外，还有一个重要的区别:由于浮点数计算有可能产生 NaN（Not a Number）值，所以比较两个浮点数时，除了大于、等于、小于之外， 还有第 4 种结果：<strong>无法比较</strong></p>
<p>fcmpg 和 fcmpl 指令的区别就在于对第 4 种结果的定义;<br>当两个 float 变量中至少有一个是 NaN 时，用 fcmpg 指令比较的结果是 1，而用 fcmpl 指令比较的结果是 -1。</p>
<h2 id="dcmp-指令"><a href="#dcmp-指令" class="headerlink" title="dcmp 指令"></a>dcmp 指令</h2><p>dcmpg 和 dcmpl 指令用来比较 double 变量,这条指令和 fcmp 指令只是比较的变量类型不同。</p>
<h2 id="if-lt-cond-gt-指令"><a href="#if-lt-cond-gt-指令" class="headerlink" title="if&lt;cond&gt;指令"></a><code>if&lt;cond&gt;</code>指令</h2><p><code>if&lt;cond&gt;</code>指令把操作数栈顶的 int 变量弹出，然后跟 0 进行比较，满足条件则跳转。假设从栈顶弹出的变量是 x，则指令执行跳转操作的条件如下：具体判定之后如何跳转,现在先不讨论;</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ifeq：x==0</span><br><span class="line">ifne：x！=0</span><br><span class="line">iflt：x&lt;0</span><br><span class="line">ifle：x&lt;=0</span><br><span class="line">ifgt：x&gt;0</span><br><span class="line">ifge：x&gt;=0</span><br></pre></td></tr></table></figure>

<h2 id="if-icmp-lt-cond-gt-指令"><a href="#if-icmp-lt-cond-gt-指令" class="headerlink" title="if_icmp&lt;cond&gt;指令"></a><code>if_icmp&lt;cond&gt;指令</code></h2><p><code>if_icmp&lt;cond&gt;</code>指令把栈顶的两个 int 变量弹出，然后进行比较，满足条件则跳转。跳转条件和 if<cond>指令类似。</cond></p>
<h2 id="if-acmp-lt-cond-gt-指令"><a href="#if-acmp-lt-cond-gt-指令" class="headerlink" title="if_acmp&lt;cond&gt;指令"></a><code>if_acmp&lt;cond&gt;指令</code></h2><p>把栈顶的两个引用弹出，根据引用是否相同进行跳转。</p>
<h1 id="控制指令"><a href="#控制指令" class="headerlink" title="控制指令"></a>控制指令</h1><p>分类:</p>
<ul>
<li>goto</li>
</ul>
<ul>
<li>tableswitch</li>
</ul>
<ul>
<li>lookupswitch</li>
</ul>
<h2 id="goto"><a href="#goto" class="headerlink" title="goto"></a>goto</h2><p>goto 指令进行无条件跳转,其操作码后是一个 int16 类型的操作数，所以需要读两个字节并转成成 int16 类型，该操作数即偏移 offset，那么接下来要执行的指令的位置为：<code>pc + offset</code></p>
<h2 id="tableswitch"><a href="#tableswitch" class="headerlink" title="tableswitch"></a>tableswitch</h2><p>Java 语言中的 switch-case 语句有两种实现方式：如果 case 值可以编码成一个索引表(索引值是连续的)，则实现成 tableswitch 指令；否则实现成 lookupswitch 指令</p>
<p>下面这个 Java 方法中的 switch-case 可以编译成 tableswitch 指令，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">chooseNear</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line"><span class="keyword">switch</span> (i) &#123;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">0</span>: <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">1</span>: <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">2</span>: <span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line">  <span class="keyword">default</span>: <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>tableswitch 后跟的操作数是对应 case 分支的跳转 offset，其格式类似于：</p>
<p>default 分支对应的跳转 defaultOffset，0 分支对应的索引 low(这里就是 0)，2 分支对应的索引 high(这里就是 2)，因为 0<del>2 分支对应的跳转是连续的，所以接下来分别对应 0</del>2 分支的跳转 offset。</p>
<p>这里用一个数组存放最合适不过了，数组大小就是<code>high-low+1</code>，这里拿到一个分支跳转的 case 的索引 index，先判断 index 在不在 low 和 high 之间，如果不在，其 offset 就是 defaultOffset，否则就用从数组中找 <code>arr[index-low]</code>，拿到对应的 offset。</p>
<h2 id="lookupswitch"><a href="#lookupswitch" class="headerlink" title="lookupswitch"></a>lookupswitch</h2><p>(索引值是非连续的)下面这个 Java 方法中的 switch-case 则需要编译成 lookupswitch 指令：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">chooseFar</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">switch</span> (i) &#123;</span><br><span class="line">  <span class="keyword">case</span> -<span class="number">100</span>: <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">0</span>: <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">100</span>: <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">default</span>: <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为这里的 case 语句并不是连续的，所以不能用数组来表示了，只能是一个 case 的索引，接下来该 case 对应的跳转。</p>
<h1 id="扩展指令"><a href="#扩展指令" class="headerlink" title="扩展指令"></a>扩展指令</h1><h2 id="wide-指令"><a href="#wide-指令" class="headerlink" title="wide 指令"></a>wide 指令</h2><p>加载类指令、存储类指令、ret 指令和 iinc 指令需要按索引访问局部变量表，索引以 uint8 的形式存在字节码中。对于大部分方法来说，<strong>局部变量表大小一般都不会超过 256</strong>，所以用一字节来表示索引就够了。</p>
<p>但是如果有方法的局部变量表超过这限制时,Java 虚拟机规范定义了 wide 指令来扩展前述指令。</p>
<p>wide 指令改变其他指令的行为，modifiedInstruction 字段存放被改变的指令。</p>
<h2 id="ifnull-ifnonnull-指令"><a href="#ifnull-ifnonnull-指令" class="headerlink" title="ifnull/ifnonnull 指令"></a>ifnull/ifnonnull 指令</h2><p>根据引用是否是 null 进行跳转，ifnull 和 ifnonnull 指令把栈顶的引用弹出。</p>
<h2 id="goto-w-指令"><a href="#goto-w-指令" class="headerlink" title="goto_w 指令"></a>goto_w 指令</h2><p>goto_w 指令和 goto 指令的唯一区别就是索引从 2 字节变成了 4 字节。</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/12/手写JVM系列-8-线程私有的运行时数据/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/12/手写JVM系列-8-线程私有的运行时数据/" itemprop="url">手写JVM系列(8)-运行时数据</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-12T22:47:02+08:00">
                2017-05-12
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,561
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>前面介绍了如何搜索和解析 class 文件，如何解析 class 文件，那么接下来就要开始实现 JVM 了，这一节我们讨论并初步实现运行时数据区（run-time data area），为接下来编写字节码解释器做准备。本节所有的<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">代码</a>均位于 runtimedata 包下。</p>
</blockquote>
<h1 id="运行时数据区概述"><a href="#运行时数据区概述" class="headerlink" title="运行时数据区概述"></a>运行时数据区概述</h1><p>运行时数据区可以分为两类：</p>
<ul>
<li>多线程共享:在 Java 虚拟机启动时创建好，在 Java 虚拟机退出时销毁。<ul>
<li>类数据，其存放在方法区(逻辑上来说,方法区也是堆中的一部分)<ul>
<li>字段</li>
<li>方法信息</li>
<li>方法字节码</li>
<li>运行时常量池</li>
</ul>
</li>
<li>类实例(对象)=&gt;堆(堆由垃圾收集器定期清理，所以程序员不需要关心对象空间的释放)</li>
</ul>
</li>
<li>线程私有:创建线程时才创建，线程退出时销毁。其主要作用是辅助执行 Java 字节码<ul>
<li>pc 寄存器：存放当前正在执行的 Java 虚拟机指令的地址，如果当前执行的是 native 方法，则 pc 的值 JVM 没有明确定义。</li>
<li>Java 虚拟机栈<ul>
<li>栈帧<ul>
<li>局部变量表</li>
<li>操作数</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p> 在任一时刻，某一线程肯定是在执行某个方法。这个方法叫作该线程的<strong>当前方法</strong>；</p>
<p>执行该方法的帧叫作线程的<strong>当前帧</strong>；</p>
<p>声明该方法的类叫作<strong>当前类</strong>。</p>
<p>如果当前方法是<strong>Java 方法</strong>，则 pc 寄存器中存放当前正在执行的 Java 虚拟机指令的地址，否则，当前方法是本地方法，pc 寄存器中的值没有明确定义。</p>
<p><img src="https://geosmart.github.io/2016/03/07/JVM%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%88%E4%BA%8C%EF%BC%89Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F%E4%B8%8E%E5%86%85%E5%AD%98%E6%BA%A2%E5%87%BA%E5%BC%82%E5%B8%B8/Java%E8%99%9A%E6%8B%9F%E6%9C%BA%E8%BF%90%E8%A1%8C%E6%97%B6%E6%95%B0%E6%8D%AE%E5%8C%BA.jpg" alt="运行时数据区示意图"></p>
<p>堆可以是连续空间，也可以不连续。堆的大小可以固定，也可以在运行时按需扩展。</p>
<p>Java 命令提供了-Xms 和-Xmx 两个非标准选项，用来调整堆的初始大小和最大大小。如果没有进行指定,那么使用默认大小;</p>
<p>虚拟机实现者可以使用任何垃圾回收算法管理堆，甚至完全不进行垃圾收集也是可以的。</p>
<h1 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h1><p>Java 虚拟机可以操作两类数据：</p>
<ul>
<li>基本类型:变量中存放数据本身。</li>
<li>引用类型:变量中存放的是对象引用，真正的对象数据是在堆里分配的。</li>
</ul>
<p>这里所说的变量包括 类变量（静态字段）、实例变量（非静态字段）、数组元素、方法的参数和局部变量等</p>
<p>引用类型可以进一步分为 3 种：</p>
<ul>
<li>类类型:指向类实例</li>
<li>接口类型:指向实现了该接口的类或数组实例</li>
<li>数组类型类:指向数组实例 </li>
</ul>
<p>引用类型有一个特殊的值——null，表示该引用不指向任何对象。</p>
<p><strong>操作数栈和局部变量表只存放数据的值,并不记录数据类型。具体操作的是什么类型的数据,反映在操作符上,eg:iadd:就是对 int 值进行加法操作.</strong></p>
<p>关于字节码和指令集的具体讲解在<a href="https://zachaxy.github.io/2017/05/13/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-9-%E6%8C%87%E4%BB%A4%E9%9B%86/">手写JVM系列(9)-指令集</a>中介绍。</p>
<p>基于 Java 虚拟机只能操作上面两种数据，并且在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/#Code">属性表</a>的 Code 属性一节中介绍过，局部变量是存放在 Slot 中的，所以这里定义一个 Slot 类，里面存放上面所述的两种变量：基本类型和引用类型。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Slot</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> num;</span><br><span class="line">    <span class="keyword">public</span> Zobject ref;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Slot</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于基本类型，使用定义的 num 变量，对于引用类型，使用 Zobject 变量，因为现在还没有涉及到实现类和对象的实现，所以这里自己定义了一个类 Zobject 来代表引用。等到后面章节中，会具体讲解实现类和对象的实现方式。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Zobject</span> </span>&#123;</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> 暂时为空实现  </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="实现线程私有的运行时数据区"><a href="#实现线程私有的运行时数据区" class="headerlink" title="实现线程私有的运行时数据区"></a>实现线程私有的运行时数据区</h1><h2 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h2><p>既然是要实现线程私有的运行时数据区，那么就要先实现线程类，这里定义 Zthread 类代表线程。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Zthread</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> pc;</span><br><span class="line">    Zstack stack; <span class="comment">//Stack 结构体（Java 虚拟机栈）的引用;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Zthread</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//默认栈的大小是 1024,也就是说可以存放 1024 个栈帧</span></span><br><span class="line">        stack = <span class="keyword">new</span> Zstack(<span class="number">1024</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getPc</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> pc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPc</span><span class="params">(<span class="keyword">int</span> pc)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.pc = pc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pushFrame</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line">        stack.push(frame);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Zframe <span class="title">popFrame</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stack.pop();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Zframe <span class="title">getCurrentFrame</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stack.top();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Zframe <span class="title">createFrame</span><span class="params">(<span class="keyword">int</span> maxLocals, <span class="keyword">int</span> maxStack)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Zframe(<span class="keyword">this</span>, maxLocals, maxStack);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里只关注其中的成员变量。我们知道线程中私有的数据包括：PC 和虚拟机栈。PC 使用一个整数保存，虚拟机栈使用了我们自定义的一个 Zstack 类，下面是其具体实现。</p>
<h2 id="Java-虚拟机栈"><a href="#Java-虚拟机栈" class="headerlink" title="Java 虚拟机栈"></a>Java 虚拟机栈</h2><p>Java 虚拟机规范对 Java 虚拟机栈的约束非常宽松。虚拟机栈可以是连续的空间，也可以不连续可以是固定大小，也可以在运行时动态扩展。Java 提供了-Xss 选项来设置 Java 虚拟机栈大小。</p>
<p>如果 Java 虚拟机栈有大小限制，且执行线程所需的栈空间超出了这个限制，会导致 StackOverflowError 异常抛出。</p>
<p>如果 Java 虚拟机栈可以动态扩展，但是内存已经耗尽，会导致 OutOfMemoryError 异常抛出。</p>
<p>这里我们用经典的链表（linked list）数据结构来实现 Java 虚拟机栈，这样栈就可以按需使用内存空间，而且弹出的帧也可被及时回收。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Zstack</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> maxSize;    <span class="comment">//虚拟机栈中所包含栈帧的最大容量</span></span><br><span class="line">    <span class="keyword">int</span> size;       <span class="comment">//当前虚拟机栈中包含帧的数量</span></span><br><span class="line">    <span class="keyword">private</span> Zframe _top; <span class="comment">//栈顶的帧</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Zstack</span><span class="params">(<span class="keyword">int</span> maxSize)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.maxSize = maxSize;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//新添加一个栈帧,将这个栈帧设置为 top,当然如果当前栈之前有元素,那么将要 push 进的 frame 的 lower 是指为之前的 top,当前 frame 变为 top;</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">push</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size &gt; maxSize) &#123;</span><br><span class="line">            <span class="comment">//throw new RuntimeException("java.lang.StackOverflowError");</span></span><br><span class="line">            <span class="comment">//如果栈已经满了，按照 Java 虚拟机规范，应该抛出 StackOverflowError 异常</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> StackOverflowError();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (_top != <span class="keyword">null</span>) &#123;</span><br><span class="line">            frame.lower = _top; <span class="comment">// frame 中保存前一个帧的引用,使得当前帧被 push 的时,前一个帧顶上去;</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        _top = frame;</span><br><span class="line">        size++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">Zframe <span class="title">pop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (_top == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> EmptyStackException();</span><br><span class="line">        &#125;</span><br><span class="line">        Zframe tmp = _top;</span><br><span class="line">        _top = tmp.lower;</span><br><span class="line">        tmp.lower = <span class="keyword">null</span>;  <span class="comment">//tmp 是带 pop 出的栈帧,既然要 pop 出来,那么将其 lower 设置为 null,不在持有栈中的帧,避免内存泄露;</span></span><br><span class="line">        size--;</span><br><span class="line">        <span class="keyword">return</span> tmp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">Zframe <span class="title">top</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (_top == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> EmptyStackException();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> _top;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中：maxSize 字段保存栈的容量（最多可以容纳多少帧），size 字段保存栈的当前大小，_top 字段保存栈顶指针。</p>
<p>push（）方法把帧推入栈顶，如果栈已经满了，按照 Java 虚拟机规范，应该抛出 StackOverflowError 异常。</p>
<p>pop（）方法把栈顶帧弹出，如果此时栈是空的，肯定是我们的虚拟机有 bug，这里我们手动抛出了一个 EmptyStackException 异常。</p>
<p>top（）方法只是返回栈顶帧，但并不弹出。</p>
<h2 id="栈帧"><a href="#栈帧" class="headerlink" title="栈帧"></a>栈帧</h2><p>上面的虚拟机栈是用单向链表实现的，栈中每一个元素都是栈帧，这里我们定义一个 Zframe 类，具体实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Zframe</span> </span>&#123;</span><br><span class="line">    Zframe lower;       <span class="comment">//当前帧的 前一帧的引用;相当于单向链表的前一个指针</span></span><br><span class="line">    LocalVars localVars;    <span class="comment">//局部变量表的引用;</span></span><br><span class="line">    OperandStack operandStack;  <span class="comment">//操作数栈的引用;</span></span><br><span class="line">    Zthread thread;</span><br><span class="line">    <span class="keyword">int</span> nextPC;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> 2017/5/4 0004</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Zframe</span><span class="params">(Zthread thread, <span class="keyword">int</span> maxLocals, <span class="keyword">int</span> maxStack)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.thread = thread;</span><br><span class="line">        localVars = <span class="keyword">new</span> LocalVars(maxLocals);</span><br><span class="line">        operandStack = <span class="keyword">new</span> OperandStack(maxStack);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> LocalVars <span class="title">getLocalVars</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> localVars;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> OperandStack <span class="title">getOperandStack</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> operandStack;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Zthread <span class="title">getThread</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> thread;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getNextPC</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> nextPC;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNextPC</span><span class="params">(<span class="keyword">int</span> nextPC)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.nextPC = nextPC;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>lower 字段用来实现链表数据结构，保存的是栈中前一个栈帧的引用，相当于链表中的 next 指针，这样当栈顶的帧出栈时，栈顶帧把其持有的 lower 帧设置为当前栈顶帧。</p>
<p>localVars 字段保存局部变量表引用。</p>
<p>operandStack 字段保存操作数栈引用。</p>
<p>在构造方法中传入了局部变量表大小和操作数栈深度，这两个值是由编译器预先计算好的，存储在 class 文件 method_info 结构的 Code 属性中。</p>
<h2 id="局部变量表"><a href="#局部变量表" class="headerlink" title="局部变量表"></a>局部变量表</h2><p>局部变量表是按索引访问的，那么我们自然也是用数组来实现。根据 Java 虚拟机规范，这个数组的每个元素至少可以容纳一个 int 或引用值，两个连续的元素可以容纳一个 long 或 double 值。这就是我们之前讲的属性表中 Code 属性中的<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/#Code">Slot</a>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Slot</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> num;</span><br><span class="line">    <span class="keyword">public</span> Zobject ref;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Slot</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>操作局部变量表和操作数栈的指令都是隐含类型信息的。下面给 LocalVars 类型定义一些方法，用来存取不同类型的变量。</p>
<ul>
<li>int 变量最简单，直接存取即可。</li>
<li>float 变量可以先转成 int 类型，然后按 int 变量来处理。</li>
<li>long 变量则需要拆成两个 int 变量（需要注意的点是将两个 int 合并成一个 long 的方式，具体处理方式见下面的源码 getLong）。</li>
<li>double 变量可以先转成 long 类型，然后按照 long 变量来处理。</li>
<li>引用值，也比较简单，直接存取即可。</li>
</ul>
<p>下面给出 LocalVars 中存取变量或引用的方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LocalVars</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Slot[] localVars; <span class="comment">//局部变量表,JVM 规定其按照索引访问,所以将其设置为数组</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LocalVars</span><span class="params">(<span class="keyword">int</span> maxLocals)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (maxLocals &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            localVars = <span class="keyword">new</span> Slot[maxLocals];</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(<span class="string">"maxLocals&lt;0"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//提供了对 int,float,long,double,引用的存取,这里要注意的是 long 和 double 是占用 8 字节的,所以使用了局部变量表中的两个槽位分别存储前四字节和后四字节</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setInt</span><span class="params">(<span class="keyword">int</span> index, <span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        Slot slot = <span class="keyword">new</span> Slot();</span><br><span class="line">        slot.num = val;</span><br><span class="line">        localVars[index] = slot;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getInt</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> localVars[index].num;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setFloat</span><span class="params">(<span class="keyword">int</span> index, <span class="keyword">float</span> val)</span> </span>&#123;</span><br><span class="line">        Slot slot = <span class="keyword">new</span> Slot();</span><br><span class="line">        slot.num = Float.floatToIntBits(val);</span><br><span class="line">        localVars[index] = slot;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">float</span> <span class="title">getFloat</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Float.intBitsToFloat(localVars[index].num);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setLong</span><span class="params">(<span class="keyword">int</span> index, <span class="keyword">long</span> val)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//先存低 32 位</span></span><br><span class="line">        Slot slot1 = <span class="keyword">new</span> Slot();</span><br><span class="line">        slot1.num = (<span class="keyword">int</span>) (val);</span><br><span class="line">        localVars[index] = slot1;</span><br><span class="line">        <span class="comment">//再存高 32 位</span></span><br><span class="line">        Slot slot2 = <span class="keyword">new</span> Slot();</span><br><span class="line">        slot2.num = (<span class="keyword">int</span>) (val &gt;&gt; <span class="number">32</span>);</span><br><span class="line">        localVars[index + <span class="number">1</span>] = slot2;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getLong</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> low = localVars[index].num;</span><br><span class="line">        <span class="keyword">long</span> high = localVars[index + <span class="number">1</span>].num;</span><br><span class="line">        <span class="keyword">return</span> ((high &amp; <span class="number">0x000000ffffffffL</span>) &lt;&lt; <span class="number">32</span>) | (low &amp; <span class="number">0x00000000ffffffffL</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setDouble</span><span class="params">(<span class="keyword">int</span> index, <span class="keyword">double</span> val)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> bits = Double.doubleToLongBits(val);</span><br><span class="line">        setLong(index, bits);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">getDouble</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> bits = getLong(index);</span><br><span class="line">        <span class="keyword">return</span> Double.longBitsToDouble(bits);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRef</span><span class="params">(<span class="keyword">int</span> index, Zobject ref)</span> </span>&#123;</span><br><span class="line">        Slot slot = <span class="keyword">new</span> Slot();</span><br><span class="line">        slot.ref = ref;</span><br><span class="line">        localVars[index] = slot;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Zobject <span class="title">getRef</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> localVars[index].ref;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意到，我们这里并没有对 boolean、byte、short 和 char 类型定义存取方法，因为这些类型的值都是转换成 int 值类来处理的。</p>
<h2 id="操作数栈"><a href="#操作数栈" class="headerlink" title="操作数栈"></a>操作数栈</h2><p>操作数栈的实现方式和局部变量表类似。操作数栈也是通过索引来访问的，操作数栈的大小是编译器已经确定的，所以依然可以用[]Slot 实现。这里有一个 size 字段是用于记录栈顶位置的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OperandStack</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> size;  <span class="comment">//初始值为 0,在运行中,代表当前栈顶的 index,还未使用,可以直接用,用完记得 size++;</span></span><br><span class="line">    <span class="keyword">private</span> Slot[] slots;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">OperandStack</span><span class="params">(<span class="keyword">int</span> maxStack)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (maxStack &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            slots = <span class="keyword">new</span> Slot[maxStack];</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(<span class="string">"maxStack&lt;0"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pushInt</span><span class="params">(<span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        Slot slot = <span class="keyword">new</span> Slot();</span><br><span class="line">        slot.num = val;</span><br><span class="line">        slots[size] = slot;</span><br><span class="line">        size++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">popInt</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        size--;</span><br><span class="line">        <span class="keyword">return</span> slots[size].num;</span><br><span class="line">    &#125;</span><br><span class="line"> 	...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>和局部变量表类似，需要定义一些方法从操作数栈中弹出，或者往其中推入各种类型的变量。这里只列举出最简单的对于 int 变量进行存取的的部分，对于其它类型的存取和局部变量表是一样的，就不在浪费篇幅了。这里要注意的一点是：每次存取数据，都要对 size 进行相应的加减操作。</p>
<h2 id="局部变量表和操作数栈实例分析"><a href="#局部变量表和操作数栈实例分析" class="headerlink" title="局部变量表和操作数栈实例分析"></a>局部变量表和操作数栈实例分析</h2><p>以下面计算圆形周长的方法为例,观察局部变量和操作数栈的变化</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">float</span> <span class="title">circumference</span><span class="params">(<span class="keyword">float</span> r)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">float</span> pi = <span class="number">3.14f</span>;</span><br><span class="line">    <span class="keyword">float</span> area = <span class="number">2</span> * pi * r;</span><br><span class="line">    <span class="keyword">return</span> area;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码被 javac 编译成如下字节码:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">00 ldc #4</span><br><span class="line">02 fstore_1</span><br><span class="line">03 fconst_2</span><br><span class="line">04 fload_1</span><br><span class="line">05 fmul</span><br><span class="line">06 fload_0</span><br><span class="line">07 fmul</span><br><span class="line">08 fstore_2</span><br><span class="line">09 fload_2</span><br><span class="line">10 return</span><br></pre></td></tr></table></figure>

<p>circumference（）方法的局部变量表大小是 3，操作数栈深度是 2;(执行方法所需的局部变量表大小和操作数栈深度是由编译器预先计算好的)</p>
<p>假设调用该方法时传入的参数是 1.6f,那么执行该方法时，操作数栈和局部变量表的变化如下：</p>
<p><img src="http://7xvxof.com1.z0.glb.clouddn.com/jvmgo_40.png" alt="circumference 方法执行过程"></p>
<p>传递给它的参数是 1.6f，方法开始执行前，1.6 被保存在本地变量表的#0 位置，接下来开始执行字节码：</p>
<p>首先是 ldc，它把 3.14f 推入栈顶</p>
<p>接着是 fstore_1 指令，它把栈顶的 3.14f 弹出，放到#1 号局部变量中</p>
<p>fconst_2 指令把 2.0f 推到栈顶</p>
<p>fload_1 指令把#1 号局部变量推入栈顶</p>
<p>fmul 指令执行浮点数乘法。它把栈顶的两个浮点数弹出，相乘，然后把结果推入栈顶</p>
<p>fload_0 指令把#0 号局部变量推入栈顶</p>
<p>fmul 继续乘法计算</p>
<p>fstore_2 指令把操作数栈顶的 float 值弹出，放入#2 号局部变量表</p>
<p>fload_2 指令把#2 号局部变量推入操作数栈顶</p>
<p>最后 freturn 指令把操作数栈顶的 float 变量弹出，返回给方法调用者。</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/12/LayoutInflater内部原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/12/LayoutInflater内部原理/" itemprop="url">LayoutInflater内部原理</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-12T22:36:24+08:00">
                2017-05-12
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  4,118
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <h1 id="LayoutInflater"><a href="#LayoutInflater" class="headerlink" title="LayoutInflater"></a>LayoutInflater</h1><p>相信大家对 LayoutInflater 并不陌生，我们在使用 ListView，RecyclerView 时，经常需要将 item 的布局文件加载到 ListView 上，这就用到了 LayoutInflater，调用 inflate 方法就可以将一项 item 添加到父控件中，那么它内部是如何实现的呢？</p>
<p>先来看一下我们平时是怎么获取 LayoutInflater 的</p>
<ul>
<li>LayoutInflater layoutInflater = LayoutInflater.from(context);</li>
<li>LayoutInflater layoutInflater = (LayoutInflater) context  .getSystemService(Context.LAYOUT_INFLATER_SERVICE); </li>
</ul>
<p>其实第一种内部是调用了第二种方法，这是一个跨进程通信的过程，因为解析布局文件这个服务是系统级的服务。</p>
<p>在获取到 LayoutInflater 之后，就可以使用其方法了,其对外提供的 inflate 方法有若干重载方法，但是最后都是调用到了下面的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">inflate(<span class="meta">@LayoutRes</span> <span class="keyword">int</span> resource, <span class="meta">@Nullable</span> ViewGroup root, <span class="keyword">boolean</span> attachToRoot)</span><br></pre></td></tr></table></figure>

<p>接下来进入 inflate 方法内部，看其如何实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> View <span class="title">inflate</span><span class="params">(@LayoutRes <span class="keyword">int</span> resource, @Nullable ViewGroup root, <span class="keyword">boolean</span> attachToRoot)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Resources res = getContext().getResources();</span><br><span class="line">    <span class="keyword">if</span> (DEBUG) &#123;</span><br><span class="line">        Log.d(TAG, <span class="string">"INFLATING from resource: \""</span> + res.getResourceName(resource) + <span class="string">"\" ("</span></span><br><span class="line">                + Integer.toHexString(resource) + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> XmlResourceParser parser = res.getLayout(resource);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> inflate(parser, root, attachToRoot);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        parser.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第 10 行，根据传入的布局文件 id，生成一个 Xml 解析器，LayoutInflater 其实就是使用 Android 提供的 pull 解析方式来解析布局文件的。接下来调用 inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法开始解析所提供的布局文件了</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br></pre></td><td class="code"><pre><span class="line">public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) &#123;</span><br><span class="line">    synchronized (mConstructorArgs) &#123;</span><br><span class="line">        Trace.traceBegin(Trace.TRACE_TAG_VIEW, &quot;inflate&quot;);</span><br><span class="line"></span><br><span class="line">        final Context inflaterContext = mContext;</span><br><span class="line">        final AttributeSet attrs = Xml.asAttributeSet(parser);</span><br><span class="line">        Context lastContext = (Context) mConstructorArgs[0];</span><br><span class="line">        mConstructorArgs[0] = inflaterContext;</span><br><span class="line">        View result = root;</span><br><span class="line"></span><br><span class="line">        try &#123;</span><br><span class="line">            // Look for the root node.</span><br><span class="line">            int type;</span><br><span class="line">            while ((type = parser.next()) != XmlPullParser.START_TAG &amp;&amp;</span><br><span class="line">                    type != XmlPullParser.END_DOCUMENT) &#123;</span><br><span class="line">                // Empty</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            if (type != XmlPullParser.START_TAG) &#123;</span><br><span class="line">                throw new InflateException(parser.getPositionDescription()</span><br><span class="line">                        + &quot;: No start tag found!&quot;);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            final String name = parser.getName();</span><br><span class="line">            </span><br><span class="line">            if (DEBUG) &#123;</span><br><span class="line">                System.out.println(&quot;**************************&quot;);</span><br><span class="line">                System.out.println(&quot;Creating root view: &quot;</span><br><span class="line">                        + name);</span><br><span class="line">                System.out.println(&quot;**************************&quot;);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            if (TAG_MERGE.equals(name)) &#123;</span><br><span class="line">                if (root == null || !attachToRoot) &#123;</span><br><span class="line">                    throw new InflateException(&quot;&lt;merge /&gt; can be used only with a valid &quot;</span><br><span class="line">                            + &quot;ViewGroup root and attachToRoot=true&quot;);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                rInflate(parser, root, inflaterContext, attrs, false);</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                // Temp is the root view that was found in the xml</span><br><span class="line">                final View temp = createViewFromTag(root, name, inflaterContext, attrs);</span><br><span class="line"></span><br><span class="line">                ViewGroup.LayoutParams params = null;</span><br><span class="line"></span><br><span class="line">                if (root != null) &#123;</span><br><span class="line">                    if (DEBUG) &#123;</span><br><span class="line">                        System.out.println(&quot;Creating params from root: &quot; +</span><br><span class="line">                                root);</span><br><span class="line">                    &#125;</span><br><span class="line">                    // Create layout params that match root, if supplied</span><br><span class="line">                    params = root.generateLayoutParams(attrs);</span><br><span class="line">                    if (!attachToRoot) &#123;</span><br><span class="line">                        // Set the layout params for temp if we are not</span><br><span class="line">                        // attaching. (If we are, we use addView, below)</span><br><span class="line">                        temp.setLayoutParams(params);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                if (DEBUG) &#123;</span><br><span class="line">                    System.out.println(&quot;-----&gt; start inflating children&quot;);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                // Inflate all children under temp against its context.</span><br><span class="line">                rInflateChildren(parser, temp, attrs, true);</span><br><span class="line"></span><br><span class="line">                if (DEBUG) &#123;</span><br><span class="line">                    System.out.println(&quot;-----&gt; done inflating children&quot;);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                // We are supposed to attach all the views we found (int temp)</span><br><span class="line">                // to root. Do that now.</span><br><span class="line">                if (root != null &amp;&amp; attachToRoot) &#123;</span><br><span class="line">                    root.addView(temp, params);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                // Decide whether to return the root that was passed in or the</span><br><span class="line">                // top view found in xml.</span><br><span class="line">                if (root == null || !attachToRoot) &#123;</span><br><span class="line">                    result = temp;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; catch (XmlPullParserException e) &#123;</span><br><span class="line">            InflateException ex = new InflateException(e.getMessage());</span><br><span class="line">            ex.initCause(e);</span><br><span class="line">            throw ex;</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            InflateException ex = new InflateException(</span><br><span class="line">                    parser.getPositionDescription()</span><br><span class="line">                            + &quot;: &quot; + e.getMessage());</span><br><span class="line">            ex.initCause(e);</span><br><span class="line">            throw ex;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            // Don&apos;t retain static reference on context.</span><br><span class="line">            mConstructorArgs[0] = lastContext;</span><br><span class="line">            mConstructorArgs[1] = null;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Trace.traceEnd(Trace.TRACE_TAG_VIEW);</span><br><span class="line"></span><br><span class="line">        return result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 6 行，创建一个 AttributeSet 对象，该对象用来保存 xml 布局中 View 中设置的属性，只不过现在只是创建了这个类，对于该类的成员变量现在还没有进行初始化，其实这个类中持有了 xmlParser(这一点要明确)，其内部封装了 getAttributeByName 等方法，并且在接下来的解析过程中从来没有显示的解析过 view 的属性，而是在反射创建 view 的过程中，传入这个 AttributeSet 对象，想要获取什么属性，直接调用 AttributeSet 的 getAttributeByXXX 的方法即可。至于和 layout 相关的属性，都不在 view 的构造方法中获取，而是在为其设置 LayoutParams 的时候，进行获取。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">LayoutParams</span><span class="params">(Context c, AttributeSet attrs)</span> </span>&#123;</span><br><span class="line">    TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);</span><br><span class="line">    setBaseAttributes(a,</span><br><span class="line">            R.styleable.ViewGroup_Layout_layout_width,</span><br><span class="line">            R.styleable.ViewGroup_Layout_layout_height);</span><br><span class="line">    a.recycle();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 9 行，将传入的第二个参数 root 赋给 result，先不管这个方法内部做了什么，总之这个方法返回值就是 result，但是也不一定就是第二个参数 root，因为该方法中间还有可能改变 result 的值。</p>
<p>第 14 行，开始解析 xml 布局文件，这里是个 while 循环，循环体中是空实现，目的是要获得该 xml 的开始节点或者结尾节点。如果不是开始或者结束，那么就一直寻找 Dom 树中的下一个节点，直到找到为止。当然这里还是为了获取开始节点，因为在第 19 行还会判断找到的是不是开始节点，不是的话直接报错了。</p>
<p>第 24 行，获取到传入的布局文件的根节点的 name</p>
<p>第 33 行，如果该节点是”merge”，会进行一次判断，因为 merge 的用法是会将 merge 节点下的所有布局全部添加到其父容器中，如果我们传入的 root 为 null，或者 attachToRoot 为 false，违背了 merge 的用法，直接报错；否则会调用 rInflate 方法解析 merge 节点中的控件，rInflate 的内部实现在下面进行分析</p>
<p>第 42 行，如果根节点不是”merge”，那么调用<code>createViewFromTag(root, name, inflaterContext, attrs)</code>方法，创建该布局根节点所代表的 View 对象 temp，createViewFromTag 方法的内部流程在下面进行解释。</p>
<p>第 46 行，判断该 inflate 方法的第二个参数 root 是否为 null，如果不为空，那么调用该 root 的 generateLayoutParams 方法产生 LayoutParams</p>
<p>第 52 行，判断该 inflate 方法的第三个参数 attachToRoot 的值，如果为 false，那么给第 42 行返回的布局的根 View 设置第 46 行创建的 LayoutParams</p>
<p>第 65 行，执行 rInflateChildren(parser, temp, attrs, true)方法，解析 temp 节点内的子 view，内部执行流程在下面进行分析</p>
<p>第 73 行，如果同时满足 root 不为 null 并且 attachToRoot 为 true，那么执行 root.addView(temp, params)，并最终返回该 root（inflate 的第二个参数）</p>
<p>第 79 行，如果 root 为 null 或者 attachToRoot 为 false，那么直接返回 temp（解析的布局文件的根节点的 View 对象）</p>
<h1 id="LayoutInflater-方法使用不同参数产生不同的效果"><a href="#LayoutInflater-方法使用不同参数产生不同的效果" class="headerlink" title="LayoutInflater 方法使用不同参数产生不同的效果"></a>LayoutInflater 方法使用不同参数产生不同的效果</h1><p>现在有如下两个布局文件：</p>
<p>activity_main.xml ：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="utf-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">LinearLayout</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:android</span>=<span class="string">"http://schemas.android.com/apk/res/android"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:id</span>=<span class="string">"@+id/activity_main"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_width</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_height</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:orientation</span>=<span class="string">"vertical"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">LinearLayout</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>button_layout.xml：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Button</span> <span class="attr">xmlns:android</span>=<span class="string">"http://schemas.android.com/apk/res/android"</span>  </span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_width</span>=<span class="string">"wrap_content"</span>  </span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_height</span>=<span class="string">"300dp"</span>  </span></span><br><span class="line"><span class="tag">    <span class="attr">android:text</span>=<span class="string">"Button"</span> &gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">Button</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>我们并没有在 LinearLayout 中添加 Button 的标签，而是将 Button 写在另一个单独的布局文件中，然后在代码中将 button 添加到上面的 LinearLayout 中,但是使用不同的 inflate 的参数，查看结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">	getWindow().requestFeature(Window.FEATURE_NO_TITLE);</span><br><span class="line">	setContentView(R.layout.activity_main);</span><br><span class="line"></span><br><span class="line">	LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);</span><br><span class="line">	Button button;</span><br><span class="line">	LayoutInflater inflater = LayoutInflater.from(<span class="keyword">this</span>);</span><br><span class="line">	<span class="comment">//（1）</span></span><br><span class="line">	button = (Button) inflater.inflate(R.layout.button_main, <span class="keyword">null</span>);</span><br><span class="line">	linearLayout.addView(button);</span><br><span class="line"></span><br><span class="line">  	<span class="comment">//（2）</span></span><br><span class="line">	inflater.inflate(R.layout.button_main, linearLayout);</span><br><span class="line">	</span><br><span class="line">  	<span class="comment">//（3）</span></span><br><span class="line">	button = (Button) inflater.inflate(R.layout.button_main, linearLayout, <span class="keyword">false</span>);</span><br><span class="line">	linearLayout.addView(button);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>显示效果如图：</p>
<h2 id="inflate-layoutId-null"><a href="#inflate-layoutId-null" class="headerlink" title="inflate(layoutId, null)"></a>inflate(layoutId, null)</h2><p>使用这个方法，没有指定父容器，现象就是第一个 button 并没有按照布局文件中设定的那样，显示 300dp 的高度。根据 inflate 方法中的第 79 行，直接将解析到 button 返回，我们直接拿到这个 button 是没有用的，想要在 LinearLayout 中显示出来，还需要调用 addView 的方法，但是此时的 button 是没有 LayoutParams 的，所以直接执行 addView，那么检查到该 button 没有 LayoutParams，会给其添加一个自带的 LayoutParams，在 LinearLayout 中，产生的默认 LayoutParams 如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> LayoutParams <span class="title">generateDefaultLayoutParams</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (mOrientation == HORIZONTAL) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (mOrientation == VERTICAL) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>关于 LayoutParams，如果不了解的话，请参考<a href="https://zachaxy.github.io/2017/05/11/%E5%AF%B9LayoutParams%E7%9A%84%E7%90%86%E8%A7%A3/">对 LayoutParams 的理解</a></p>
<p>我们的线性布局是纵向的，所以宽度是父容器宽度，高度是包裹内容，结果正是我们看到的第一个 button 的效果；</p>
<h2 id="inflate-layoutId-root"><a href="#inflate-layoutId-root" class="headerlink" title="inflate(layoutId, root )"></a>inflate(layoutId, root )</h2><p>使用这个方法，指定了父容器为 LinearLayout，inflate 方法中如果使用了两个参数的方法，那么第三个参数 attachToRoot 的值默认为 true</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> View <span class="title">inflate</span><span class="params">(@LayoutRes <span class="keyword">int</span> resource, @Nullable ViewGroup root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> inflate(resource, root, root != <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时 root 不为 null 所以 attachToRoot 为 true，满足 inflate 方法中第 73 行的条件，所以为 button 的 LayoutParams 与 LinearLayout 进行关联，从而满足了 button 的 300dp 的高度，结果就是现实的第二个 button 的效果。</p>
<h2 id="inflate-layoutId-root-false"><a href="#inflate-layoutId-root-false" class="headerlink" title="inflate(layoutId, root, false )"></a>inflate(layoutId, root, false )</h2><p>使用这个方法，root 不为空，但是 attachToRoot 为 false，所以调用了 inflate 方法中第 52 行的逻辑，为这个 view 添加了 root 的 LayoutParams，并返回该 view，之前也说过，一个 View 如果没有与父容器关联的 LayoutParams，那么这个 view 是没有办法使用的。所以在这里要比第二种方法多了一步手动 addView 的方法，所以这样和第二种效果是一样的，只是 attachToRoot 的值，如果为 true，inflate 时自动帮我们添加到 root 中，为 false，那么返回的 view 需要我们手动执行一次 root.addView 方法才可以，当然这里我们也可以将 view 解析出来之后，不调用 root 的 addView 方法，而是调用其它 ViewGroup 的 addView 方法，但是这样感觉有点混乱，如果想调用其它 ViewGroup 的 addView 方法，何不在 inflate 时，将 root 设置为我们真正的 ViewGroup。</p>
<h1 id="在-inflate-方法中炸出的几个方法"><a href="#在-inflate-方法中炸出的几个方法" class="headerlink" title="在 inflate 方法中炸出的几个方法"></a>在 inflate 方法中炸出的几个方法</h1><h2 id="createViewFromTag"><a href="#createViewFromTag" class="headerlink" title="createViewFromTag"></a>createViewFromTag</h2><blockquote>
<p>该方法的作用是根据解析到的布局文件的节点名（eg：RelativeLayout，TextView，com.your.coustom.view 等）创建对应的 Java 对象，在 Java 中如何根据类名创建对象呢？很显然是用反射来实现的。这就是 createViewFromTag 所完成的功能，其将解析到对应的 View 返回。</p>
</blockquote>
<p>那么接下来深入源码，看一下其具体流程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> View temp = createViewFromTag(root, name, inflaterContext, attrs);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> View <span class="title">createViewFromTag</span><span class="params">(View parent, String name, Context context, AttributeSet attrs)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> createViewFromTag(parent, name, context, attrs, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function">View <span class="title">createViewFromTag</span><span class="params">(View parent, String name, Context context, AttributeSet attrs,<span class="keyword">boolean</span> ignoreThemeAttr)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (name.equals(<span class="string">"view"</span>)) &#123;</span><br><span class="line">		name = attrs.getAttributeValue(<span class="keyword">null</span>, <span class="string">"class"</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Apply a theme wrapper, if allowed and one is specified.</span></span><br><span class="line">	<span class="keyword">if</span> (!ignoreThemeAttr) &#123;</span><br><span class="line">		<span class="keyword">final</span> TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);</span><br><span class="line">		<span class="keyword">final</span> <span class="keyword">int</span> themeResId = ta.getResourceId(<span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">	<span class="keyword">if</span> (themeResId != <span class="number">0</span>) &#123;</span><br><span class="line">		context = <span class="keyword">new</span> ContextThemeWrapper(context, themeResId);</span><br><span class="line">		&#125;</span><br><span class="line">	ta.recycle();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (name.equals(TAG_1995)) &#123;</span><br><span class="line">   		 <span class="comment">// Let's party like it's 1995!</span></span><br><span class="line">   	 	<span class="keyword">return</span> <span class="keyword">new</span> BlinkLayout(context, attrs);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">    	View view;</span><br><span class="line">        <span class="keyword">if</span> (mFactory2 != <span class="keyword">null</span>) &#123;</span><br><span class="line">       		 view = mFactory2.onCreateView(parent, name, context, attrs);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (mFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">        	view = mFactory.onCreateView(name, context, attrs);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        	view = <span class="keyword">null</span>;</span><br><span class="line">   		 &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (view == <span class="keyword">null</span> &amp;&amp; mPrivateFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">    	view = mPrivateFactory.onCreateView(parent, name, context, attrs);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (view == <span class="keyword">null</span>) &#123;</span><br><span class="line">   		 <span class="keyword">final</span> Object lastContext = mConstructorArgs[<span class="number">0</span>];</span><br><span class="line">   		 mConstructorArgs[<span class="number">0</span>] = context;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">    	<span class="keyword">if</span> (-<span class="number">1</span> == name.indexOf(<span class="string">'.'</span>)) &#123;</span><br><span class="line">    	view = onCreateView(parent, name, attrs);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">   		 view = createView(name, <span class="keyword">null</span>, attrs);</span><br><span class="line">   		 &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">   		 mConstructorArgs[<span class="number">0</span>] = lastContext;</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> view;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InflateException e) &#123;</span><br><span class="line">		<span class="keyword">throw</span> e;</span><br><span class="line">	&#125; <span class="keyword">catch</span> (ClassNotFoundException e) &#123;</span><br><span class="line">		<span class="keyword">final</span> InflateException ie = <span class="keyword">new</span> InflateException(attrs.getPositionDescription()</span><br><span class="line">			+ <span class="string">": Error inflating class "</span> + name);</span><br><span class="line">          ie.initCause(e);</span><br><span class="line">          <span class="keyword">throw</span> ie;</span><br><span class="line"></span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		<span class="keyword">final</span> InflateException ie = <span class="keyword">new</span> InflateException(attrs.getPositionDescription()</span><br><span class="line">			+ <span class="string">": Error inflating class "</span> + name);</span><br><span class="line">		ie.initCause(e);</span><br><span class="line">		<span class="keyword">throw</span> ie;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 30 行，开始解析我们的 view 了，这里是使用不同的 mFactory 来创建 View，优先顺序为：mFactory2=》mFactory=》mPrivateFactory，哪个 Factory 不为空，就用哪个，调用其 createView 方法，通过反射创建相应的对象，createView 方法就不在往下跟了，要不这篇就解不了了，后面有时间会写一篇关于插件换肤的文章，会对 createView 方法进一步深入。</p>
<p>总之，你要记住结论，那就是 createViewFromTag 方法根据布局文件解析到的节点名，通过反射创建相应的对象。</p>
<h2 id="rInflate"><a href="#rInflate" class="headerlink" title="rInflate"></a>rInflate</h2><blockquote>
<p>回顾调用 rinflate 方法的地方，是在解析布局文件时，根 tag 为”merge”，我们知道 merge 必须是某个布局文件的根 tag，其下包含的所有的子 view 们直接添加到其父容器中，这样就减少了一层布局的嵌套。在单独的一个布局文件中，merge 的表现类似于 FrameLayout。那么根据这个特性，解析时直接跳过 merge 这一层，进入内部，继续解析具体的 view。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">rInflate(parser, root, inflaterContext, attrs, false);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">void rInflate(XmlPullParser parser, View parent, Context context,</span><br><span class="line">		AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException &#123;</span><br><span class="line"></span><br><span class="line">	final int depth = parser.getDepth();	//这个 depth 的值，估计是 2，因为 merge 作为根标签，其 depth 是 1，现在进入了 merge 的内部，所以为 2</span><br><span class="line">	int type;</span><br><span class="line"></span><br><span class="line">	while (((type = parser.next()) != XmlPullParser.END_TAG ||</span><br><span class="line">			parser.getDepth() &gt; depth) &amp;&amp; type != XmlPullParser.END_DOCUMENT) &#123;</span><br><span class="line"></span><br><span class="line">		if (type != XmlPullParser.START_TAG) &#123;</span><br><span class="line">			continue;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		final String name = parser.getName();</span><br><span class="line">		</span><br><span class="line">		if (TAG_REQUEST_FOCUS.equals(name)) &#123;</span><br><span class="line">			parseRequestFocus(parser, parent);</span><br><span class="line">		&#125; else if (TAG_TAG.equals(name)) &#123;</span><br><span class="line">			parseViewTag(parser, parent, attrs);</span><br><span class="line">		&#125; else if (TAG_INCLUDE.equals(name)) &#123;</span><br><span class="line">			if (parser.getDepth() == 0) &#123;</span><br><span class="line">				throw new InflateException(&quot;&lt;include /&gt; cannot be the root element&quot;);</span><br><span class="line">			&#125;</span><br><span class="line">			parseInclude(parser, context, parent, attrs);</span><br><span class="line">		&#125; else if (TAG_MERGE.equals(name)) &#123;</span><br><span class="line">			throw new InflateException(&quot;&lt;merge /&gt; must be the root element&quot;);</span><br><span class="line">		&#125; else &#123;</span><br><span class="line">			final View view = createViewFromTag(parent, name, context, attrs);</span><br><span class="line">			final ViewGroup viewGroup = (ViewGroup) parent;</span><br><span class="line">			final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);</span><br><span class="line">			rInflateChildren(parser, view, attrs, true);</span><br><span class="line">			viewGroup.addView(view, params);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	if (finishInflate) &#123;</span><br><span class="line">		parent.onFinishInflate();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 7 行，拿到当前标签的深度，其深度在这里是 2，因为已经跳过了跟标签 merge，进去其内部了，xml 的深度示意图如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- outside --&gt;</span>     0</span><br><span class="line"><span class="tag">&lt;<span class="name">root</span>&gt;</span>               1</span><br><span class="line">  sometext           1</span><br><span class="line">    <span class="tag">&lt;<span class="name">foobar</span>&gt;</span>         2</span><br><span class="line">      ...			 2</span><br><span class="line">    <span class="tag">&lt;/<span class="name">foobar</span>&gt;</span>        2</span><br><span class="line"><span class="tag">&lt;/<span class="name">root</span>&gt;</span>              1</span><br><span class="line"><span class="comment">&lt;!-- outside --&gt;</span>     0</span><br></pre></td></tr></table></figure>

<p>第 23 行，主要这里解释了如果解析到的 tag 是 include，那么并且其深度为 0，那么直接抛出异常，这表明 include 标签是不能作为根标签的。只能作为子标签，接下来开始调用 parseInclude 方法解析 include 指定的布局文件，内部依旧是类似于 createViewFromTag 的方法通过反射不断的创建 view 对象，这里不再深入。</p>
<p>第 31 行，这里调用了 createViewFromTag 的方法，创建了 merge 标签下的 view，并将该 view 添加到 rinflate 方法的第二个参数 root 中，其调用了 root.addView(view)，如果该 view 是一个 ViewGroup，其内部还有其它子 view，会调用 rInflateChildren 方法，继续解析该 view 下的子 view，最终结果相当于直接将 merge 标签下的子元素添加到 merge 标签 parent 中，这样就保证了不会引入额外的层级。</p>
<h2 id="rInflateChildren"><a href="#rInflateChildren" class="headerlink" title="rInflateChildren"></a>rInflateChildren</h2><blockquote>
<p>该方法被调用的时机是在当解析到一个 ViewGroup 类型的标签时（eg：LinearLayout 等），那么会调用该方法，继续解析该 ViewGroup 下的标签。其内部的实现很简单，直接调用了上面的 rinflate 方法，以当前解析的到 ViewGroup 作为该方法的第二个参数 root，进行解析。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">rInflateChildren</span><span class="params">(XmlPullParser parser, View parent, AttributeSet attrs,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="keyword">boolean</span> finishInflate)</span> <span class="keyword">throws</span> XmlPullParserException, IOException </span>&#123;</span><br><span class="line">    rInflate(parser, parent, parent.getContext(), attrs, finishInflate);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="总结：解析-XML-布局文件的作用"><a href="#总结：解析-XML-布局文件的作用" class="headerlink" title="总结：解析 XML 布局文件的作用"></a>总结：解析 XML 布局文件的作用</h1><p>本节以 LayoutInflater 方法的不同参数抛出问题，引出 LayoutInflater 内部的执行流程，并解释了 inflate 方法中的几个解析布局文件的关键方法，然后又根据 inflate 不同的参数，观察其不同的现象。相信此刻你对于 LayoutInflater 的使用以及其内部的执行原理已经很清楚了。接下来再做一个总结</p>
<p>当我们用 LayoutInflater 解析一个布局文件的时候到底做了什么，简单的一句话就是：<strong>将布局映射成一棵多叉树</strong>。</p>
<p>inflate 方法的核心就是根据不同的标签，反射出不同的 View 对象。那么采用何种方法，才能表现 xml 布局文件中，父容器中和子 View 的包含关系呢？</p>
<p>答案就是使用了 ViewGroup#addView 方法，如果解析的 View 是一个 ViewGroup，那么会将该 ViewGroup 作为 parent，继续解析内部的 view，并将其添加到了 ViewGroup#mChilddren 数组中，这个数组默认长度为 12，如果子 view 数量过多，会对该数组进行扩容，都是以 12 进行扩充。如果子 View 依然是一个 ViewGroup，那么继续执行上面的过程，这个过程就是<strong>深度优先遍历</strong>，将整个布局文件映射为一棵树，每个父节点必定是一个 ViewGroup，其对应的子节点就是在该 ViewGroup 标签下的 View，其引用保存在该 ViewGroup 的 mChildren 数组中，这样就形成了一棵多叉树，其根节点就是布局文件的根节点。</p>
<p>最后附上一张inflate的内部执行流程图</p>
<p><img src="http://opda1q948.bkt.clouddn.com/LayoutInflater.png" alt="inflate方法内部执行流程图"></p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/11/对LayoutParams的理解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/11/对LayoutParams的理解/" itemprop="url">对LayoutParams的理解</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-11T09:33:25+08:00">
                2017-05-11
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,471
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <h1 id="LayoutParams-是什么？"><a href="#LayoutParams-是什么？" class="headerlink" title="LayoutParams 是什么？"></a>LayoutParams 是什么？</h1><p>相信很多人都有疑惑，LayoutParams 是什么？不知道大家想过没有，如果定义一个 ViewGroup，然后在这个 ViewGroup 中放若干 view，这些 view 在 ViewGroup 中的大小关系是保存在哪里的呢？</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">LinearLayout</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:android</span>=<span class="string">"http://schemas.android.com/apk/res/android"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:tools</span>=<span class="string">"http://schemas.android.com/tools"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:id</span>=<span class="string">"@+id/activity_main"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_width</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_height</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:orientation</span>=<span class="string">"vertical"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">tools:context</span>=<span class="string">"com.zx.readsourcecode.MainActivity"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">TextView</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:id</span>=<span class="string">"@+id/tv"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:layout_width</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:layout_height</span>=<span class="string">"wrap_content"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:text</span>=<span class="string">"文字"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">LinearLayout</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面是一段最简单不过的布局文件，这里我们最常用的一个属性<code>android:layout_width</code>和<code>android:layout_height</code>相信大家再熟悉不过，其实这两个属性对应两个变量 width 和 height，那么这两个变量是哪个类的成员变量呢？答案就是 LayoutParams。虽然之前不知道 LayoutParams 这和类的存在，但是却一直偷偷的使用它。</p>
<h1 id="LayoutParams-的作用"><a href="#LayoutParams-的作用" class="headerlink" title="LayoutParams 的作用"></a>LayoutParams 的作用</h1><p> <strong>LayoutParams 是 View 用来告诉它的父控件如何放置自己的。</strong>基类 LayoutParams（也就是 ViewGroup.LayoutParams）仅仅描述了这个 View 想要的宽度和高度。在 View 的测量过程中，LayoutParams 起到了决定性的作用！</p>
<p>注意：<code>android:layout_width</code>和<code>android:layout_height</code>表面看起来是 TextView 的宽度和高度，相信这是很多人误解的地方，但如果是描述自己的宽高，那么属性名直接定义为<code>android:width</code>和<code>android:height</code>不就行了，为什么前面要加<code>layout_</code>的前缀？这是因为 TextView 既然放在 LinearLayout 中，那么它的宽度和高度并不是由自己决定的，而是由其父容器（这里对应 LinearLayout）来决定的。通过该属性可选的值 <code>match_parent</code>可以看出，这并不是一个具体的值，而是描述为和父容器一样宽，所以宽度是看父容器有多宽，才给子 view 设置多宽的。</p>
<p>而描述 View 直接用它们自己的属性就好了，如<code>textColor</code>和<code>text</code>等等，为什么还需要引入 LayoutParams 呢？因为<code>textColor</code>和<code>text</code>等这样的属性都是只与 TextView 自身有关的，无论这个 TextView 处于什么环境，这些属性都是不变的。而<code>layout_width</code>与<code>layout_marginLeft</code>这样的属性是与它的父控件息息相关的，是父控件通过 LayoutParams 提供这些”layout_”属性给孩子们用的；是父控件根据孩子们的要求（LayoutParams）来决定怎么测量。</p>
<p>所以在 xml 布局中，凡是以<code>layout_</code>开头的属性，均不是 view 自身的，而是它所在的父控件的 LayoutParams 类中的属性，这里的父控件一定是 ViewGroup 的一个子类。</p>
<h1 id="ViewGroup-LayoutParams"><a href="#ViewGroup-LayoutParams" class="headerlink" title="ViewGroup.LayoutParams"></a>ViewGroup.LayoutParams</h1><p>LayoutParams 是 ViewGroup 中的一个静态类，而每个 ViewGroup 的子类（eg：LinearLayout，FrameLayout，RelativeLayout 等）中依然有一个各自的 LayoutParams 的子类，其在 ViewGroup 的 LayoutParams 静态类的基础之上，添加了和具体布局相关的属性，比如 LinearLayout 中特有的 layout_weight 属性，用来指定特定方向的分配比例，再比如 RelativeLayout 特有的 layout_left，用来指定当前 view 和其它子 view 相对位置的属性等。进入源码中看一下 ViewGroup 中静态内部类 LayoutParams。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public static class LayoutParams &#123;</span><br><span class="line"></span><br><span class="line">    @SuppressWarnings(&#123;&quot;UnusedDeclaration&quot;&#125;)</span><br><span class="line">    @Deprecated</span><br><span class="line">    public static final int FILL_PARENT = -1;</span><br><span class="line"></span><br><span class="line">    public static final int MATCH_PARENT = -1;</span><br><span class="line"></span><br><span class="line">    public static final int WRAP_CONTENT = -2;</span><br><span class="line"></span><br><span class="line">    public int width;</span><br><span class="line"></span><br><span class="line">    public int height;</span><br><span class="line">    </span><br><span class="line">    public LayoutParams(Context c, AttributeSet attrs) &#123;</span><br><span class="line">    TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);</span><br><span class="line">    </span><br><span class="line">    	setBaseAttributes(a,</span><br><span class="line">   			 R.styleable.ViewGroup_Layout_layout_width,</span><br><span class="line">   		 	R.styleable.ViewGroup_Layout_layout_height);</span><br><span class="line">    </span><br><span class="line">    	a.recycle();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public LayoutParams(int width, int height) &#123;</span><br><span class="line">        this.width = width;</span><br><span class="line">        this.height = height;</span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到其内部的成员变量只有最基本的 width 和 height，对应了布局文件中的<code>android:layout_width</code>和<code>android:layout_height</code>的值，在解析布局文件时，遇到这两个属性，就给对应的 LayoutParams 的这两个成员变量进行赋值了。</p>
<p>在 ViewGroup 中还自带了一个 LayoutParams 的子类 MarginLayoutParams，供不同的布局使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MarginLayoutParams</span> <span class="keyword">extends</span> <span class="title">ViewGroup</span>.<span class="title">LayoutParams</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> leftMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> topMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> rightMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> bottomMargin;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> startMargin = DEFAULT_MARGIN_RELATIVE;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> endMargin = DEFAULT_MARGIN_RELATIVE;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其添加了 Margin 相关的属性，相对于布局文件的<code>android:layout_marginLeft=&quot;5dp&quot;</code>等属性。</p>
<p><code>LayoutParams</code>其实是父控件提供给子 view 的，好让子 view 选择如何测量和放置自己。所以在子 view 添加到父控件的那一刻，子 view 就应该有<code>LayoutParams</code>了。我们来看看几中常见的在代码中添加 View 的方式：还是上面的布局，这次我们不用 xml，而是用代码来实现一样的效果。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);</span><br><span class="line">TextView textView = <span class="keyword">new</span> TextView(<span class="keyword">this</span>);</span><br><span class="line">LinearLayout.LayoutParams params = <span class="keyword">new</span> LinearLayout.LayoutParams(</span><br><span class="line">        LinearLayout.LayoutParams.MATCH_PARENT,</span><br><span class="line">        LinearLayout.LayoutParams.WRAP_CONTENT);</span><br><span class="line">linearLayout.addView(textView, params);</span><br></pre></td></tr></table></figure>

<p>View 要是想被添加到 ViewGroup 中，是不可能脱离相应的 ViewGroup.LayoutParams，而独立存在的，不信你将布局文件中的<code>android:layout_width</code>和<code>android:layout_height</code>这两个属性删掉，编译器立即报错。</p>
<p>同时在代码中添加上述操作，虽然可以使用如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);</span><br><span class="line">TextView textView = <span class="keyword">new</span> TextView(<span class="keyword">this</span>);</span><br><span class="line">linearLayout.addView(textView);</span><br></pre></td></tr></table></figure>

<p>但是我们追到 addView 方法内部看一下，可以得出结论，调用 addView（view）的方法，对应的 ViewGroup子类会通过 generateDefaultLayoutParams（）方法自动添加一个默认的 LayoutParams。不同的 ViewGroup（这里指的是 LinearLayout）产生具体 LayoutParams 的方法不同。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View child)</span> </span>&#123;</span><br><span class="line">    addView(child, -<span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View child, <span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (child == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Cannot add a null child view to a ViewGroup"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    LayoutParams params = child.getLayoutParams();</span><br><span class="line">    <span class="keyword">if</span> (params == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	params = generateDefaultLayoutParams();</span><br><span class="line">    <span class="keyword">if</span> (params == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"generateDefaultLayoutParams() cannot return null"</span>);</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    addView(child, index, params);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不同的 ViewGroup（布局）产生具体 LayoutParams 的方法不同。看一下 LinearLayout 中的 generateDefaultLayoutParams（）是如何添加的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> LayoutParams <span class="title">generateDefaultLayoutParams</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很简单的添加了一个宽高均为 wrap_content 的属性。</p>
<p><strong>注：generateDefaultLayoutParams 方法中返回的 LayoutParams 类，是具体的 ViewGroup 子类（这里代表 LinearLayout）中的静态类 LayoutParams，而不是 ViewGroup 中的。</strong></p>
<p>在深入到 addView 中，看一下 view 和 LayoutParams 是如何关联的，这里删除了部分代码，只看主线；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addViewInner</span><span class="params">(View child, <span class="keyword">int</span> index, LayoutParams params,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="keyword">boolean</span> preventRequestLayout)</span> </span>&#123;  </span><br><span class="line"></span><br><span class="line">	<span class="comment">//(1)</span></span><br><span class="line">    <span class="keyword">if</span> (child.getParent() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"The specified child already has a parent. "</span> +</span><br><span class="line">                <span class="string">"You must call removeView() on the child's parent first."</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//(2)</span></span><br><span class="line">    <span class="keyword">if</span> (!checkLayoutParams(params)) &#123;</span><br><span class="line">        params = generateLayoutParams(params);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  	<span class="comment">//(3)preventRequestLayout 参数的默认值是 false；</span></span><br><span class="line">    <span class="keyword">if</span> (preventRequestLayout) &#123;</span><br><span class="line">        child.mLayoutParams = params;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        child.setLayoutParams(params);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  	<span class="comment">//(4)默认值为 -1</span></span><br><span class="line">    <span class="keyword">if</span> (index &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        index = mChildrenCount;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//(5)</span></span><br><span class="line">    addInArray(child, index);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//(6) tell our children，默认值为 false；</span></span><br><span class="line">    <span class="keyword">if</span> (preventRequestLayout) &#123;</span><br><span class="line">        child.assignParent(<span class="keyword">this</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        child.mParent = <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//(7)</span></span><br><span class="line">    dispatchViewAdded(child);</span><br><span class="line"> </span><br><span class="line">  <span class="comment">//......</span></span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里看一下 addViewInner 方法内部的执行流程</p>
<ol>
<li>检查 view 是否被别的 ViewGroup 添加过，如果被别的添加过，那么抛出异常</li>
<li>再对 layoutParams 进行检测，如果为 null，执行 generateLayoutParams(params)，这也是最后一次为 view 创建 params 了，这里添加的是 ViewGroup.LayoutParams，一般在 LinearLayout、RelativeLayout 等已有的布局中，addview 中会先执行类似的为 view 创建 params 的方法，添加的是各布局特有的 LayoutParams，但是如果是我们自定义的 ViewGroup，也许没有实现配套的 LayoutParams，所以最后用的是 ViewGroup 中自带的 LayoutParams</li>
<li>将 view 的 layoutParams 设置为当前的 layoutParams，在这里执行了关联</li>
<li>除非我们在 addView(view,index)指定了具体值，否则 index 默认值为 -1，如果是 -1 的话，这一步将 index 改为 ViewGroup 中当前 child view 的总和</li>
<li>ViewGroup 中有一个数组，保存着其所有子 view，这里根据 index 值添加到相应的位置，当然这里也涉及到了数组扩容问题，如果你手动指定的 index 过大，超过了当前 ViewGroup 的 mChildrenCount，那么直接报错，index 过大</li>
<li>为 view 分配 parent，这个 parent 就是添加该子 view 的 ViewGroup</li>
<li>执行了 addView 方法，那么原有的 ViewGroup 的结构势必会发生改变，这时候会执行一个回调，通知当前 ViewGroup 添加或者移除了一个 view；当然这个回调默认是 null，我们可以手动添加该回调，使用<code>setOnHierarchyChangeListener(OnHierarchyChangeListener listener)</code></li>
</ol>
<h1 id="自定义-LayoutParams"><a href="#自定义-LayoutParams" class="headerlink" title="自定义 LayoutParams"></a>自定义 LayoutParams</h1><p>前面提到，每个 ViewGroup 的子类（eg：LinearLayout，FrameLayout，RelativeLayout 等）中依然有一个各自的静态内部类 xxxLayout.LayoutParams，其继承了 ViewGroup#LayoutParams，并根据具体的布局，新增了相关属性，比如 LinearLayout 中特有的 layout_weight 属性，用来指定特定方向的分配比例，再比如 RelativeLayout 特有的 layout_left、layout_right 等，用来指定当前 view 和其它子 view 相对位置的属性等。</p>
<p>前面分析 addView 的流程中也介绍到子 view 要想添加到父容器中，父容器必定会给子 view 指定一个 LayoutParams，脱离了 LayoutParams，view 无法单独存在，view 可以通过其 getLayoutParams 方法获取其父容器为子 view 绑定的 LayoutParams。</p>
<p>使用 Android 官方提供的这些 ViewGroup（eg：LinearLayout，FrameLayout，RelativeLayout 等）在 addView 时都会为 view 设置一个 xxxLayout.LayoutParams，而在我们自定义 ViewGroup 控件的时候，如果没有为自定义的 ViewGroup 添加配套的 LayoutParams，那么最终在执行 addViewInner 方法时，会为 view 添加 ViewGroup#LayoutParams，这个 LayoutParams 是一个最基础的，只有 width 和 height 属性，如果我们想实现自定义的 ViewGroup 特殊需求，那么自定义 LayoutParams 是必不可少的。</p>
<p>关于如何自定义 LayoutParams，以及在自定义 LayoutParams 时要注意哪些问题，请参考实战案例<a href>自定义 ViewGroup——百分比布局</a>，这篇文章会根据具体的 ViewGroup 的功能需求，制定对应的 LayoutParams。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>LayoutParams 的作用：是 View 用来告诉它的父控件如何放置自己的，理解这一点很重要，因为这是 view 在 measure 和 layout 过程中很重要的因素。</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>



  </section>


  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/8/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/8/">8</a><span class="page-number current">9</span><a class="page-number" href="/page/10/">10</a><span class="space">&hellip;</span><a class="page-number" href="/page/13/">13</a><a class="extend next" rel="next" href="/page/10/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>





        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">





      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>





    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>











  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
